<template>
  <div>
    <el-dialog width="700px" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag
      :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-zhifu"></i>
        <span>{{ actionType }}{{ title }}</span>
      </span>
      <el-tabs v-model="activeName">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules" label-position="right">
        <el-col :span="12">
            <el-form-item label="标题" prop="title" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.title" placeholder="" :disabled="detailType === 'check'"></el-input>
            </el-form-item>
        </el-col>
          <el-col :span="12">
              <el-form-item label="日期" prop="date" :label-width="formlabelWidth">
                <el-date-picker style="width:100%;" v-model="formBaseData.date" type="date"
                  value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="detailType === 'check'"></el-date-picker>
              </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--            <el-form-item label="备注" prop="remark" :label-width="formlabelWidth">-->
<!--              <el-input class="fill" type="textarea" :autosize="{ minRows: 6, maxRows: 20 }" placeholder=""-->
<!--                v-model="formBaseData.remark" :disabled="detailType === 'check'">-->
<!--              </el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="19" style="position: relative" class="safeFileUpload">
            <el-form-item label="附件" :label-width="formlabelWidth">
              <cmsUploadFile ref="fileOne" :detail-id="detailId" :fileSystem="fileSystem['one']" :disabled="detailType === 'check'|| detailType === 'approve'" type="mul" :fileList="fileList" info="支持上传 png/jpg/gif/doc/xlsx/ppt/pdf等文件" :detail-type="detailType" />
            </el-form-item>
            <div class="button-group" style="position: absolute;bottom: 14px;right: -100px">
              <div style="margin-top: 5px;" v-for="(item, index) in fileListArray" :key="index">
                <el-button size="mini" @click="viewFile(item.id)">预览</el-button>
                <el-button size="mini" @click="dlFile(item.link)">下载</el-button>
              </div>
            </div>
          </el-col>
          <div style="clear:both;"></div>
        </el-form>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <!--新建和编辑的暂存上报-->
        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', { flag: 1 })"><i
              class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-guanbi"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail (value) {
      this.formBaseData.contractId = value.params.contractId

      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      this.actionType = value.typeName

      // 详情的流程操作处理
      this.detailActions.splice(0, this.detailActions.length)
      if (value.params) {
        for (let key in value.params.actions) {
          if (key !== 'show' && key !== 'update' && key !== 'getHistory') {
            this.$set(this.detailActions, this.detailActions.length, {
              name: value.params.actions[key].name,
              url: value.params.actions[key].url,
              key: key,
            })
          }
        }
      }
      // 详情id
      this.detailId = value.params === undefined ? 0 : value.params.detailId
      // 非新建详情时 获取详情
      if (this.detailType === 'history') {
        this.detailType = 'check'
        // 获取历史版本
        this.getHistoryDetail()
      } else if (this.detailType !== 'build') {
        // 获取详情请求
        this.getDetail();
      }
    }
  },
  data () {
    return {
      actionType: '查看',
      title: '季度奖惩情况',
      //存放图片的数组
      fileListArray: [],
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      activeName: 'first', //
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth: '73px', // 表单左侧标题宽度
      selectList: {
        file: [], // 文件
        approver: [], // 审批人
        structureType: [], // 结构类型
        projectTypeList: [],
      },
      isPopContainer: false,
      isShowVideo: false,
      videoFlag: false,

      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'quarterAward',
          part: 'one',
          compoName: 'fileOne'
        }
      },
      fileList: [],
      fileList_video: [],
      // 文件系统的参数
      // 所有下拉框列表的集合
      formBaseData: {
        contractId: '',//合同id
        title: '',//标题
        date: '',//培训时间
        participantUser: '',//培训人
        trainingLocation: '',//培训地点

        remark: '',//内容

      }, // 表单基本信息内容
      formBaseRules: {
          date: [
          { required: true, message: '请选择日期', trigger: 'blur' },
        ],
          title: [
              { required: true, message: '请输入标题', trigger: 'blur' },
          ],
      }, // 表单基本信息验证
      isLoading: false

    }
  },
  mounted () {

  },
  methods: {
    //点击行时触发自动选中
    clickHookRow (row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 获取详情请求 api
    getDetail () {
      this.$httpGet(
        `/buss/quarterReward/getOne?id=${this.detailId}`,
        {}).then(res => {
          if (res.code === 200) {
            let data = res.data
            // 表单信息
              this.formBaseData.remark = data.remark
              this.formBaseData.date = data.date
              this.formBaseData.title = data.title
            // 文件系统
            this.loadFiles();
            this.$forceUpdate()
          } else {
            this.$messageError(res.data.message)
          }
        }).catch(res => {
          console.log(res, '===')
          this.$messageError(this.$route.name + '请求失败')
        })
    },
    loadFiles() {
      this.$nextTick(() => {
        for (let k in this.fileSystem) {
          let fileProp = this.fileSystem[k]
          this.$refs[fileProp.compoName].init()
        }
      })
    },
    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail (type, callback) {
      let submit = '/buss/quarterReward/add'
      let postData = {}
      if (this.detailType === 'build') {
        submit = '/buss/quarterReward/add'
      } else {
        submit = '/buss/quarterReward/edit'
      }
      postData = {
        id: this.detailId,
        date: this.formBaseData.date,
        title: this.formBaseData.title,
        remark: this.formBaseData.remark,
      }
      this.isLoading = true
      this.$httpPost(submit,
        postData).then(res => {
          if (res.code === 200) {
            if (this.detailType !== 'approve') this.$messageSuccess('保存成功')
            this.detailId = !this.detailId ? res.data.id : this.detailId
            if (callback) callback()
          } else {
            this.$messageError(res.data.message)
          }
        }).catch(res => {
          console.log('请求出现错误', res);
          this.$messageError(this.$route.name + '请求失败')
        })
        .finally(() => {
          this.isLoading = false
        })
    },

    handleVideoPreview () {
      this.formBaseData.video.url = this.fileList_video[0].url
      this.formBaseData.video.show = true
    },
    showPopContainer () {
      this.isPopContainer = true;
    },
    hiddenPopContainer () {
      this.isPopContainer = false;
    },
    // 事件处理的api请求
    sealDealHttp (url, query, params, callback) {
      this.$httpPost(
        this.$store.state.httpHost.buss + url + query,
        params
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log(res)
      })
    },
    // 点击各个流程的按钮事件
    handleClickDeal (type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            contractId: '',//合同id
            title: '',//标题
            remark: '',//内容
            trainingDate: '',//培训时间
            participantUser: '',//培训人
            trainingLocation: '',//培训地点
          } // 表单基本信息内容
          // 清空文件
          this.selectList.file = []
          this.fileList_video = []
          // 关闭弹窗
          this.formShow = false
          //清空按钮 数组
          this.fileListArray = []
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              let files = []
              console.log(this.selectList.file)
              this.selectList.file.forEach(item => {
                files.push(item.id)
              })
              // 提交详情
              this.submitDetail(flag, () => {
                this.$forceUpdate()
                this.saveFiles()
                let files1 = []
                this.fileList_video.forEach(item => {
                  files1.push(item.id)
                })
                if (this.detailType === 'build') {
                  //this.$publicUpload.bindFile(files1, this.detailId)
                }
                this.isLoading = false
                this.formShow = false

                //清空按钮 数组
                this.fileListArray = []
                // 传值给父组件刷新列表
                this.$emit('reloadList')
              })
            } else {
            }
          })
          break
        // 删除
        case 'delete':
          this.$prompt('删除理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({ value }) => {
            if (value === null || value === '') {
              this.$messageError('请填写删除理由后重试')
              return
            }
            this.sealDealHttp(res.url, ``, {}, {
              id: this.detailId,
              description: value,
            }, () => {
              this.$messageSuccess('删除成功!')
              this.$forceUpdate()
              this.formShow = false
              //清空按钮 数组
              this.fileListArray = []
              // 传值给父组件刷新列表
              this.$emit('reloadList')
            })
          }).catch(() => {
            console.log('请求出现错误',);
          });
          break
      }
    },
    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        this.$refs[fileProp.compoName].saveAll(this.detailId)
      }
    },
    //下载文件
    dlFile (e) {
      var popup = window.open(",")
      popup.location.href = this.$store.state.httpHost.file + e
      setTimeout(function () {
        popup.close();
      }, 1000);
      // window.open(window.open(this.$store.state.httpHost.file+e))
    },
    //项目宣传视频
    upload_vedio (file) {


      this.beforeUploadVideo(file, this.fileList_video, '项目宣传视频')
    },
    changeVideo (val) {
      this.$set(this, 'fileList_video', [...val])
    },
    //上传前回调
    beforeUploadVideo (file, ary, part) {
      var fileSize = file.size / 1024 / 1024 < 500;
      if (['video/mp4'].indexOf(file
        .type) == -1) {
        this.$messageError("请上传正确的mp4视频格式");
        return false;
      }
      if (ary.length >= 1) {
        this.$messageError("只能上传一个视频");
        return false;
      }
      if (!fileSize) {
        this.$messageError("视频大小不能超过500MB");
        return false;
      }
      this.isShowUploadVideo = false;
      let url = ''
      url = this.$publicUpload.uploadFile
      url(
        file,
        this.fileSystem.entityClass,
        this.fileSystem.viewByAnon,
        this.fileSystem.longLife,
        this.detailId,
        this.fileSystem.module,
        part,
        file.name,
        this.fileSystem.sys)
        .then(res => {
          console.log(res)
          if (res.data.status === 1) {
            ary.push({
              name: file.name,
              size: file.size,
              url: this.$store.state.httpHost.file + res.data.data.link,
              id: res.data.data.id,
              link: res.data.data.link
            })
            console.log(ary)
            // 非新建时绑定文件
            console.log(this.fileList_video)
            if (this.detailType !== 'build') {
              this.$publicUpload.bindFile(res.data.data.id, this.detailId)
              // this.bingFileForm([res.data.id], part)
            }
            this.isShowVideo = true;
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch(res => {
          console.log('请求出现错误', res);
          this.$messageError(this.$route.name + '上传文件前-请求失败')
        })
    },


    // 删除文件时解绑文件
    removeFile (file, fileList) {
      console.log(file, fileList)
      this.unBingFile(file.id)
      this.selectList.file = fileList
      /* *
      * 删除附件之后，按钮数组同步赋值
      * */
      this.fileListArray = fileList
    },



  },

  filters: {
    numFilter (value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [], counter = 0;
        num = (num || 0).toString().split('');
        for (let i = num.length - 1; i >= 0; i--) {
          counter++;
          result.unshift(num[i]);
          if (!(counter % 3) && i != 0) {
            result.unshift(',');
          }
        }
        let after = numSmall === undefined ? result.join('') : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ""
      }
    },
    numFilter2 (value) {
      try {
        let before = value.toFixed(2)
        return before
      } catch (e) {
        return ""
      }
    }
  },
  created () {

  },
}
</script>

<style scoped lang="scss">
.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}

.el-input__inner {
  width: 291px;
}

.dialogTableDiv {
  width: 100%;
  margin: 0 auto;

  .tableTitle {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    p {
      font-size: 16px;
    }

    .add {
      background-color: #ffffff;
      color: rgb(73, 163, 250);
    }
  }
}


/*.tree-menu {*/
/*color: black !important;*/
/*div{*/
/*color: black !important;*/
/*}*/
/*}*/
</style>
<style lang="scss">
.el-message-box {
  .el-message-box__btns {
    .el-button {
      font-size: 14px;
    }
  }
}
</style>
